var express = require('express');
var router = express.Router();
var formidable = require('formidable');
var fs = require('fs'),
    TITLE = '图片上传',
    domain = "http://localhost:8089/";//上传地址
    AVATAR_UPLOAD_FOLDER = '/image/';//上传文件夹
var app=express();
app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', req.headers.origin || '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization,Origin,Accept,X-Requested-With');
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.header('Access-Control-Allow-Credentials', true);
    res.header('X-Powered-By', ' 3.2.1');
    res.header('Content-Type', 'application/json;charset=utf-8');
    if (req.method === 'OPTIONS') {
        res.sendStatus(200);
    } else {
        next();
    }
  });
router.all('/',function(req,res){
    res.send({
        msg:'欢迎上传图片'
    })
})
//上传图片
router.post('/addimg', function (req, res) {
    var form = new formidable.IncomingForm(); //创建上传表单
    form.encoding = 'utf-8'; //设置编辑
    form.uploadDir = 'public' + AVATAR_UPLOAD_FOLDER;
    //form.uploadDir = '/home/fruit_shop/public/dist/image/'; //设置上传目录
    form.keepExtensions = true; //保留后缀
    form.maxFieldsSize = 4 * 1024 * 1024; //文件大小
    form.parse(req, function (err, fields, files) {
        if (err) {
            res.locals.error = err;
            res.send({
                status: 4,
                msg: '上传失败',
                data: []
            })
            return;
        }
        console.log(files);
        console.log('path', files.file.path);
        var extName = ''; //后缀名
        switch (files.file.type) {
            case 'image/jpg':
                extName = 'jpg';
                break;
            case 'image/jpeg':
                extName = 'jpg';
                break;
            case 'image/png':
                extName = 'png';
                break;
            case 'image/x-png':
                extName = 'png';
                break;
        }
        console.log(form.uploadDir);
        console.log(`you are right`);
        if (extName == null) {
            res.locals.error = '只支持png和jpg格式图片';
            // res.render({ title: TITLE });
            return;
        }
        var avatarName = Math.random() + '.' + extName;
        //图片写入地址；
        var newPath = form.uploadDir + avatarName;
        //显示地址；
        var showUrl = domain + AVATAR_UPLOAD_FOLDER + avatarName;
        //console.log(showUrl)
        console.log("newPath", newPath);
        fs.renameSync(files.file.path, newPath); //重命名
        res.send({
            status: 3,
            msg: '上传成功',
            data: showUrl
        })
        
        // fs.linkSync(newPath,function(err){
        //     if(err){
        //         throw err;
        //     }
        //     console.log('图片删除成功')
        // })
    });
    return;
});

module.exports = router;